from fastapi.responses import StreamingResponse
from PIL import Image
import io
import os
import random
from fastapi import FastAPI, HTTPException

app = FastAPI()


def get_image_files(image_dir: str) -> list:
    return [os.path.join(image_dir, f) for f in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, f))]


def resize_and_crop_image(image_path: str, target_width: int, target_height: int) -> Image.Image:
    with Image.open(image_path) as img:
        # Convert RGBA to RGB (JPEG does not support RGBA)
        if img.mode == 'RGBA':
            img = img.convert('RGB')

        # Determine which side is the limiting factor
        scale_ratio = min(img.width / target_width, img.height / target_height)

        # Calculate new size keeping aspect ratio
        new_width = int(img.width / scale_ratio)
        new_height = int(img.height / scale_ratio)
        img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)

        # Calculate crop area and convert to integer
        left = int((new_width - target_width) / 2)
        top = int((new_height - target_height) / 2)
        right = int((new_width + target_width) / 2)
        bottom = int((new_height + target_height) / 2)

        img_cropped = img.crop((left, top, right, bottom))
        return img_cropped


@app.get("/random-image/")
async def random_image(width: int = 100, height: int = 100):
    image_dir = r'D:\Code\StarBlog\starblog\StarBlog.Web\wwwroot\media\picture_library'
    image_files = get_image_files(image_dir)
    if not image_files:
        raise HTTPException(status_code=404, detail="No images found")

    selected_image = random.choice(image_files)
    img = resize_and_crop_image(selected_image, width, height)

    img_byte_arr = io.BytesIO()
    img.save(img_byte_arr, format='JPEG')
    img_byte_arr = img_byte_arr.getvalue()

    return StreamingResponse(io.BytesIO(img_byte_arr), media_type="image/jpeg")


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000)
